package com.guodi.map.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.minio.util.MinioUtil;
import com.guodi.core.tool.api.R;
import com.guodi.map.entity.MapSceneFile;
import com.guodi.map.service.IMapSceneFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author ApLuSz
 * @描述：三维场景模块附件控制类
 * @作者: 卢顺
 * @日期: 2022-12-06
 */
@Validated
@RestController
@RequestMapping("/MapSceneFile")
@Api(value = "API - MapSceneFileController", tags = "三维场景模块附件表")
public class MapSceneFileController  extends BaseController {

    @Autowired
    private IMapSceneFileService iMapSceneFileService;


    /**
     * @描述: 获取文件数据
     * @入参:
     * @出参:
     * @作者: 卢顺
     * @日期: 2022-12-06
     **/
    @PostMapping("/entityByParentId")
    @ApiOperation(value = "获取文件数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "上级目录id", required = true, dataType = "string", paramType = "query"),
    })
    public R entityByParentId(String parentId){
        LambdaQueryWrapper<MapSceneFile> lambdaQueryWrapper = new QueryWrapper().lambda();
        lambdaQueryWrapper.eq(MapSceneFile::getParentId,parentId);
        List<MapSceneFile> mapSceneFiles = iMapSceneFileService.list(lambdaQueryWrapper);
        return R.data(mapSceneFiles);
    }


    /**
     * @描述: 上传文件
     * @入参:
     * @出参:
     * @作者: 卢顺
     * @日期: 2022-12-06
     **/
    @PostMapping("/upload")
    @ApiOperation(value = "上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "文件名称名称", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "上级目录id", required = true, dataType = "string", paramType = "query"),
    })
    public R upload(@RequestParam(required = false, value = "file") MultipartFile file,String parentId) throws Exception{
        MapSceneFile mapSceneFile = new MapSceneFile();
        mapSceneFile.setId(UuidUtil.get32UUID());
        if(null != file){
            // 文件上传
            int index = file.getOriginalFilename().lastIndexOf(".");
            String fileType = file.getOriginalFilename().substring(index + 1).toLowerCase();
            String fileId = MinioUtil.uploadFile(file.getInputStream(),"map-project-file", file.getOriginalFilename());
            if(StringUtils.isBlank(fileId)){
                return R.fail(StatusCode.REQUEST_CODE_OPERATION_FAILURE,"数据上传失败！");
            }
            mapSceneFile.setFileSize((double) file.getSize());
            mapSceneFile.setFileFormat(fileType);
            mapSceneFile.setFilePath(fileId);
            //获取上传原始文件名
            if (StringUtils.isBlank(mapSceneFile.getName())) {
                String uploadName = file.getOriginalFilename().substring(0, index);
                mapSceneFile.setName(uploadName);
            }
            if(StringUtils.isNotBlank(parentId)){
                mapSceneFile.setParentId(parentId);
            }else{
                mapSceneFile.setParentId(UuidUtil.get32UUID());
            }
        }
        iMapSceneFileService.save(mapSceneFile);
        return R.data(mapSceneFile);
    }

    /**
     * @描述: 单文件下载
     * @入参:
     * @出参:
     * @作者: 文件下载
     * @日期: 2022-12-06
     **/
    @PostMapping("/downloadFile")
    @ApiOperation(value = "单文件下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "当前文件名称", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "filePath", value = "路径", required = true, dataType = "string", paramType = "query")
    })
    public void downloadFile(String fileName, String filePath, HttpServletResponse response) throws UnsupportedEncodingException {
        // 获取文件后缀
        String fileExtentName = filePath.substring(filePath.lastIndexOf(".") + 1);
        if (!fileName.contains(".")){
            fileName += "." + fileExtentName;
        }
        filePath = URLDecoder.decode(filePath,"utf-8");
        InputStream inputStream = MinioUtil.download(filePath);
        int len = 0;
        byte [] buff=new byte[1024];
        try{
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            while((len=inputStream.read(buff))!=-1){
                out.write(buff, 0, len);
            }
            out.flush();
            out.close();
            inputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * @描述: 根据主键删除文件
     * @入参: ids
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2021-01-19
     **/
    @PostMapping("/deleteFile")
    @ApiOperation(value = "根据主键删除文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "string", paramType = "query")
    })
    public R delete(String id){
        MapSceneFile mapSceneFile = iMapSceneFileService.getById(id);
        if (mapSceneFile != null) {
            if ( StringUtils.isNotBlank(mapSceneFile.getFilePath())) {
                MinioUtil.removeFile(mapSceneFile.getFilePath());
            }
        }
        iMapSceneFileService.removeById(id);
        return R.data(null);
    }
}
